package com.gmall.pay.service;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.github.wxpay.sdk.WXPayUtil;
import com.gmall.common.result.Result;
import com.gmall.model.payment.PaymentInfo;
import okhttp3.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.HashMap;
import java.util.Map;

@Service
@RefreshScope
public class WXPayService {


    @Value("${wxpay.appid}")
    String appId;

    @Value("${wxpay.mch_id}")
    String mch_id;

    @Value("${wxpay.partnerkey}")
    String partnerkey;

    @Value("${wxpay.notifyurl}")
    String notifyUrl;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public Result<Map> unifiedorder(String orderId,
                                    Integer amount) throws Exception {
        System.out.println("订单号："+orderId);

        OkHttpClient okHttpClient = new OkHttpClient();//Postman

        //Map 转为XML
        Map map = new HashMap<>();
        map.put("appid",appId);
        map.put("mch_id",mch_id);
        map.put("nonce_str", WXPayUtil.generateNonceStr());//防止重放攻击
        map.put("body","测试商品");
        map.put("out_trade_no", String.valueOf(orderId));//商户系统内唯一
        map.put("total_fee","1");//订单总金额，单位为分
        map.put("spbill_create_ip","127.0.0.1");//发起支付的机器IP
        map.put("notify_url",notifyUrl);//支付结果通知
        map.put("trade_type","NATIVE");//扫码支付

        map.put("sign",WXPayUtil.generateSignature(map,partnerkey));

        String body = WXPayUtil.mapToXml(map);//Map 转为XML

        System.out.println(body);
        System.out.println("-------------------");
        RequestBody requestBody = RequestBody.create(body,
                MediaType.parse("application/xml; charset=utf-8")
        );//请求体
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/unifiedorder")
                .post(requestBody)
                .build();//请求

        Response response = okHttpClient.newCall(request).execute();//发送同步请求

        String responseBody_string = response.body().string();

        System.out.println(responseBody_string);

        Map<String, String> responseMap = WXPayUtil.xmlToMap(responseBody_string);

        Map mapReturn = new HashMap();
        String return_code = responseMap.get("return_code");
        String return_msg = responseMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = responseMap.get("result_code");
            if(return_code.equalsIgnoreCase("SUCCESS")){
                String code_url = responseMap.get("code_url");
                System.out.println(code_url);

                mapReturn.put("qrcode",genQrCodeAsBase64(code_url));
            }else {
                System.out.println("错误信息："+return_msg);
            }
        }else{
            System.out.println("错误信息："+return_msg);
        }
        return Result.ok(mapReturn);
    }

    public Result<Map> orderquery(@PathVariable Long orderId) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .build();//postman 构建HTTP 客户端

        MediaType mediaType = MediaType.parse("application/xml");
        Map map = new HashMap<>();
        map.put("appid",appId);
        map.put("mch_id",mch_id);
        map.put("nonce_str", WXPayUtil.generateNonceStr());//重放攻击

        map.put("out_trade_no", String.valueOf(orderId));
        String signature = WXPayUtil.generateSignature(map, partnerkey);
        map.put("sign", signature);

        String request_body =WXPayUtil.mapToXml(map);
        System.out.println(request_body);

        RequestBody requestBody = RequestBody.create(mediaType,request_body);
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/orderquery")
                .post(requestBody)
                .build();//构建请求 URL+POST+RequestBody

        Response response = okHttpClient.newCall(request).execute(); //点击执行，获取响应
        int code = response.code();// 状态码
        System.out.println("code=" + code);
        String message = response.message();//消息
        System.out.println("message=" + message);
        ResponseBody responseBody = response.body();
        String response_body = responseBody.string();//ResponseBody

        System.out.println(response_body);
        Map<String, String> responseMap = WXPayUtil.xmlToMap(response_body);
        String return_code = responseMap.get("return_code");
        String return_msg = responseMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = responseMap.get("result_code");
            if(result_code.equalsIgnoreCase("SUCCESS")){
                String trade_state = responseMap.get("trade_state");
                /*
                SUCCESS--支付成功
                REFUND--转入退款
                NOTPAY--未支付
                CLOSED--已关闭
                REVOKED--已撤销(刷卡支付)
                USERPAYING--用户支付中
                PAYERROR--支付失败(其他原因，如银行返回失败)
                 */
                System.out.println(trade_state);
                if(trade_state.equalsIgnoreCase("SUCCESS")){
                    String trade_state_desc = responseMap.get("trade_state_desc");
                    String total_fee = responseMap.get("total_fee");
                    System.out.println(trade_state_desc);

                    this.paySuccess(orderId);


                    return Result.ok(responseMap);
                }
            }
        }
        return Result.ok(responseMap);//查询成功
    }
    public String genQrCodeAsBase64(String code_url){

        QrConfig qrConfig
                = new QrConfig();
        qrConfig.setHeight(350);
        qrConfig.setWidth(350);
        String base64 = QrCodeUtil.generateAsBase64(code_url, qrConfig, "png");

        System.out.println(base64);

        return base64;

    }

    public synchronized void paySuccess(Long orderId){
        //1、新增一条支付日志 向payment_info表中新增一条数据
        //select * from payment_info where order_id = ?
        // insert into payment_info(order_id,payment_type,trade_no,payment_status,create_time,callback_time)
        PaymentInfo paymentInfo = new PaymentInfo();

        Map map1 = new HashMap();
        map1.put("orderId",orderId);
        rabbitTemplate.convertAndSend(
                "Exchange_Fanout_PaySuccess","",map1);

        //2、支付成功后，修改订单状态为已支付 order_info order_status PAID
        //3、释放锁定库存（先不做）
        /**
         * NOT_USED("未使用"),
         * USE_RUN("使用中" ),
         * USED("已使用");
         */
        //4、把优惠卷改为已使用  USE_RUN  -->USED
    }
}
